import * as sqlite3 from 'sqlite3';
import { promisify } from 'util';

const db = new sqlite3.Database('./bazi-test/bazi_data.db');
const dbGet = promisify(db.get.bind(db));
const dbAll = promisify(db.all.bind(db));

async function getDatabaseTitles(bookCode: string): Promise<string[]> {
  const rows = await dbAll(`SELECT DISTINCT title FROM paragraphs WHERE book_code = ? ORDER BY title`, [bookCode]);
  return rows.map((row: any) => row.title);
}

async function getApiResult(bazi: string): Promise<any> {
  const response = await fetch(`http://localhost:3000/api/docs/query?bazi=${encodeURIComponent(bazi)}`);
  return await response.json();
}

async function compare() {
  const bazi = '乙巳丙戌甲戌乙亥';
  
  console.log(`\n=== 分析八字: ${bazi} ===\n`);
  
  const apiResult = await getApiResult(bazi);
  
  for (let i = 1; i <= 11; i++) {
    const bookCode = `b${String(i).padStart(2, '0')}`;
    const dbTitles = await getDatabaseTitles(bookCode);
    const apiTitles = apiResult[bookCode] || [];
    
    console.log(`\n--- ${bookCode.toUpperCase()} ---`);
    console.log(`数据库标题数: ${dbTitles.length}`);
    console.log(`API返回标题数: ${apiTitles.length}`);
    console.log(`API返回标题: ${JSON.stringify(apiTitles, null, 2)}`);
    
    // 检查API返回的标题是否在数据库中
    const missingInDb: string[] = [];
    for (const apiTitle of apiTitles) {
      if (!dbTitles.includes(apiTitle)) {
        missingInDb.push(apiTitle);
      }
    }
    
    if (missingInDb.length > 0) {
      console.log(`❌ API返回但数据库中不存在的标题: ${JSON.stringify(missingInDb, null, 2)}`);
    } else {
      console.log(`✅ API返回的标题都在数据库中`);
    }
    
    // 显示数据库中所有可能的标题（前20个）
    if (dbTitles.length > 0) {
      console.log(`数据库中的标题（前20个）: ${dbTitles.slice(0, 20).join(', ')}`);
    }
  }
  
  db.close();
}

compare().catch(console.error);

